import re
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from bs4 import BeautifulSoup
import pandas

newsarr = []
driver = webdriver.Chrome(r"C:\Users\Administrator\AppData\Local\Google\Chrome\Application\chromedriver")
wait = WebDriverWait(driver, 10)

def search():
    try:
        driver.get('https://www.taobao.com/')
        input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#q")))
        submit = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#J_TSearchForm > div.search-button > button")))
        input.send_keys("美食")
        submit.click()
        total_page = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#mainsrp-pager > div > div > div > div.total")))
        gets_product()
        return total_page.text
    except TimeoutException:
        return search()

def next_page(page_number):
    try:
        input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#mainsrp-pager > div > div > div > div.form > input")))
        submit = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#mainsrp-pager > div > div > div > div.form > span.btn.J_Submit")))
        input.clear()
        input.send_keys(page_number)
        submit.click()
        wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > ul > li.item.active > span'), str(page_number)))
        gets_product()
        newstable = gets_product()
        return newstable.to_excel('taobaofood.xlsx')
    except TimeoutException:
        return next_page(page_number)

def gets_product():
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#mainsrp-itemlist > div")))
    webhtml = driver.page_source
    items = BeautifulSoup(webhtml, 'html.parser').find(class_="grid g-clearfix")
    for item in items.find_all(class_='ctx-box J_MouseEneterLeave J_IconMoreNew'):
        pd = {
            'title': item.select('a')[0].text,
            'price': item.select('strong')[0].text,
            'people': item.select('div')[2].text[:-3],
            'place': item.find(class_='').text
        }

        newsarr.append(pd)
    newstable = pandas.DataFrame(newsarr, columns=['title', 'price', 'people', 'place'])
    print(newstable)
    return newstable
def main():
    total = search()
    total = int(re.compile('(\d+)').search(total).group(1))
    for i in range(2, total+1):
        next_page(i)
if __name__ == '__main__':
    main()



